/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bdl;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.JOptionPane;

/**
 *
 * @author olawale
 */
public class DataAccess {

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("MPredictionPU");
    EntityManager em = emf.createEntityManager();

    private static DataAccess dataAccess;

    public static DataAccess getDataAccess(){
        if(dataAccess == null){
            try{
                dataAccess = new DataAccess();
            }catch(Exception ex){
                System.out.println(ex);
                int end = (ex.toString().length() > 1000) ? 1000 : ex.toString().length();
                JOptionPane.showMessageDialog(null, "The program could not start. " +
                        "There was an error connecting to the database. Details of the error below \n\n"
                        + ex.toString().substring(0, end), "Error loading MPrediction", JOptionPane.ERROR_MESSAGE);
                System.exit(1);

            }
        }
        return dataAccess;
    }

    public void persist(Object object) {
        em.getTransaction().begin();
        try {
            em.persist(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
//            em.close();
        }
    }


}
